package stark.app.function.castscreen;

import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.hpplay.sdk.source.api.IConnectListener;
import com.hpplay.sdk.source.api.LelinkPlayerInfo;
import com.hpplay.sdk.source.api.LelinkSourceSDK;
import com.hpplay.sdk.source.browse.api.IBrowseListener;
import com.hpplay.sdk.source.browse.api.LelinkServiceInfo;
import com.stark.cast.screen.CastScreenManager;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.constants.MediaType;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.interfaces.OnSelectResultListener;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import stark.app.MediaSelectUtil;
import stark.app.R;
import stark.app.databinding.ActivityCastScreenDemoBinding;
import stark.common.basic.base.BaseNoModelActivity;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.UriUtil;

/**
 * Author：daizhongbin on 2021/9/7
 * Email：1027154338@qq.com
 * Desc: 投屏demo界面
 */
public class CastScreenDemoActivity extends BaseNoModelActivity<ActivityCastScreenDemoBinding> {

    /**------------------------下面为乐播平台的--------------------------------*/
    //替换成自己的应用的App id
    private static final String TEST_APP_ID = "19197";//官方demo包名为“com.amfun”对应的appid"18065";
    //替换成自己的应用的App secret
    private static final String TEST_APP_SECRET = "c6654622032eec867863de12a428f081";//官方demo包名为“com.amfun”对应的appsecret"5af8bfd6bd26518f26f89b795de6fc0c";

    /**------------------------下面为网旭科技公司平台的--------------------------------*/
//    //替换成自己的应用的App id
//    private static final String TEST_APP_ID = "factory_6343eede1c02d5ab66507975";
//    //替换成自己的应用的App secret
//    private static final String TEST_APP_SECRET = "98EF0-F6647-9538C-B68ED";



    private static final int REQ_PUSH_LOCAL_MUSIC = 1;

    private CastScreenManager mCastScreenManager;
    private CastScreenServiceAdapter mServiceAdapter;
    private LelinkServiceInfo mSelServiceInfo;

    @Override
    protected int onCreate() {
        return R.layout.activity_cast_screen_demo;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCastScreenManager.deInit();
    }

    @Override
    protected void initView() {
        enableBrowseBtns(false);
        enableConnectBtns(false);
        enablePushMirrorBtns(false);

        CastScreenManager.init(TEST_APP_ID, TEST_APP_SECRET);
        mCastScreenManager = CastScreenManager.getInstance();
        mCastScreenManager.setListener(new CastScreenManager.AListener() {

            @Override
            public void onInit(boolean success) {
                hideDialog();
                ToastUtils.showLong(success ? "初始化成功" : "初始化失败");
                if (success) {
                    enableBrowseBtns(true);
                }
            }

            @Override
            public void onBrowse(int code, List<LelinkServiceInfo> list) {
                hideDialog();
                if (code == IBrowseListener.BROWSE_SUCCESS) {
                    if (mServiceAdapter != null) {
                        mServiceAdapter.setNewInstance(list);
                    }
                } else if (code == IBrowseListener.BROWSE_TIMEOUT) {
                    ToastUtils.showLong("搜索超时");
                } else if (code == IBrowseListener.BROWSE_ERROR_AUTH || code == IBrowseListener.BROWSE_ERROR_AUTH_TIME) {
                    ToastUtils.showLong("认证失败");
                }
            }

            @Override
            public void onConnect(LelinkServiceInfo lelinkServiceInfo, int connectType) {
                String strProtocol = "未知协议";
                switch (connectType) {
                    case IConnectListener.TYPE_LELINK:
                        strProtocol = "乐联协议";
                        break;
                    case IConnectListener.TYPE_DLNA:
                        strProtocol = "DLNA 协议";
                        break;
                    case IConnectListener.TYPE_IM:
                        strProtocol = "IM协议";
                        break;
                }
                ToastUtils.showLong("已连接设备" + lelinkServiceInfo.getName() + ",连接协议为：" + strProtocol);
                enablePushMirrorBtns(true);
            }

            @Override
            public void onDisconnect(LelinkServiceInfo lelinkServiceInfo, int what, int extra) {
                enablePushMirrorBtns(false);
                String text = "已断开设备" + lelinkServiceInfo.getName();
                if (what == IConnectListener.WHAT_HARASS_WAITING) {// 防骚扰，等待用户确认
                    // 乐播投屏防骚扰等待消息
                    text = lelinkServiceInfo.getName() + "等待用户确认";
                } else if (what == IConnectListener.WHAT_DISCONNECT) {
                    switch (extra) {
                        case IConnectListener.EXTRA_HARASS_REJECT:// 防骚扰，用户拒绝投屏
                            text = lelinkServiceInfo.getName() + "连接被拒绝";
                            break;
                        case IConnectListener.EXTRA_HARASS_TIMEOUT:// 防骚扰，用户响应超时
                            text = lelinkServiceInfo.getName() + "防骚扰响应超时";
                            break;
                        case IConnectListener.EXTRA_HARASS_BLACKLIST:// 防骚扰，该用户被加入黑名单
                            text = lelinkServiceInfo.getName() + "已被加入投屏黑名单";
                            break;
                        default:
                            text = lelinkServiceInfo.getName() + "连接断开";
                            break;
                    }
                } else if (what == IConnectListener.WHAT_CONNECT_FAILED) {
                    switch (extra) {
                        case IConnectListener.EXTRA_CONNECT_DEVICE_OFFLINE:
                            text = lelinkServiceInfo.getName() + "不在线";
                            break;
                        default:
                            text = lelinkServiceInfo.getName() + "连接失败";
                            break;
                    }
                }

                ToastUtils.showLong(text);
            }
        });
        showDialog("初始化中...");
        mCastScreenManager.init();

        //搜索
        mDataBinding.btnBrowse.setOnClickListener(v -> {
            showDialog("设备搜索中...");
            mCastScreenManager.startBrowse();
        });
        //停止搜索
        mDataBinding.btnStopBrowse.setOnClickListener(v -> {
            mCastScreenManager.stopBrowse();
        });
        //连接设备
        mDataBinding.btnConnect.setOnClickListener(v -> {
            if (mSelServiceInfo == null) {
                ToastUtils.showLong("请先选中你要连接的设备");
                return;
            }
            mCastScreenManager.connect(mSelServiceInfo);
        });
        //断开连接的设备
        mDataBinding.btnDisconnect.setOnClickListener(v -> {
            mCastScreenManager.disConnect();
        });
        //推送网络图片
        mDataBinding.btnPushNetImg.setOnClickListener(v -> {
            String url = "http://cdn.hpplay.com.cn/demo/1080P.png";
            pushPlay(url, false, LelinkSourceSDK.MEDIA_TYPE_IMAGE);
        });
        //推送网络视频
        mDataBinding.btnPushNetVideo.setOnClickListener(v -> {
            String url = "http://cdn.hpplay.com.cn/demo/lbtp.mp4";
            pushPlay(url, false, LelinkSourceSDK.MEDIA_TYPE_VIDEO);
        });
        //推送本地音频
        mDataBinding.btnPushLocalMusic.setOnClickListener(v -> {
            IntentUtil.pickAudio(this, REQ_PUSH_LOCAL_MUSIC);
        });
        //推送网络音频
        mDataBinding.btnPushNetMusic.setOnClickListener(v -> {
            String url = "http://cdn.hpplay.com.cn/demo/bedroom.mp3";
            pushPlay(url, false, LelinkSourceSDK.MEDIA_TYPE_AUDIO);
        });
        //推送本地图片或是视频
        mDataBinding.btnPush.setOnClickListener(v -> {
            MediaSelectUtil.pickMedia(this, PhotoConfig.Mode.ALL, 1, new OnSelectResultListener<List<SelectMediaEntity>>() {
                @Override
                public void onResult(List<SelectMediaEntity> data) {
                    if (data == null || data.size() == 0) {
                        return;
                    }
                    SelectMediaEntity entity = data.get(0);
                    int type = LelinkSourceSDK.MEDIA_TYPE_VIDEO;
                    if (entity.getType() == MediaType.Type.IMAGE) {
                        type = LelinkSourceSDK.MEDIA_TYPE_IMAGE;
                    }
                    pushPlay(entity.getTargetPath(), true, type);
                }
            });
        });
        //镜像（当前乐播sdk不支持镜像功能，如需获得支持，需提供每个应用每年6万的费用）
        mDataBinding.btnMirror.setOnClickListener(v -> {
            LelinkPlayerInfo playerInfo = new LelinkPlayerInfo();
            //playerInfo.setAutoBitrate(true);
            mCastScreenManager.startMirror(playerInfo);
        });

        //recycleView
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mDataBinding.rvService.setLayoutManager(layoutManager);

        mServiceAdapter = new CastScreenServiceAdapter();
        mServiceAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                mSelServiceInfo = mServiceAdapter.getItem(position);
                mServiceAdapter.setSelPos(position);
                enableConnectBtns(true);
            }
        });
        mDataBinding.rvService.setAdapter(mServiceAdapter);

    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQ_PUSH_LOCAL_MUSIC) {
                Uri uri = data.getData();
                if (uri == null) return;
                pushPlay(uri.toString(), true, LelinkSourceSDK.MEDIA_TYPE_AUDIO);
            }
        }
    }

    private void pushPlay(String url, boolean isLocalFile, int mediaType) {
        LelinkPlayerInfo playerInfo = new LelinkPlayerInfo();
        playerInfo.setType(mediaType);
        if (isLocalFile) {
            Uri uri = Uri.parse(url);
            if (UriUtil.isContentSchemeUri(uri)) {
                playerInfo.setLocalUri(uri);
            } else {
                playerInfo.setLocalPath(url);
            }
        } else {
            playerInfo.setUrl(url);
        }
        mCastScreenManager.startPlay(playerInfo);
    }

    private void enableConnectBtns(boolean enabled) {
        mDataBinding.btnConnect.setEnabled(enabled);
        mDataBinding.btnDisconnect.setEnabled(enabled);
    }

    private void enablePushMirrorBtns(boolean enabled) {
        mDataBinding.btnPushNetImg.setEnabled(enabled);
        mDataBinding.btnPushNetVideo.setEnabled(enabled);
        mDataBinding.btnPushLocalMusic.setEnabled(enabled);
        mDataBinding.btnPushNetMusic.setEnabled(enabled);
        mDataBinding.btnPush.setEnabled(enabled);
        //mDataBinding.btnMirror.setEnabled(enabled);
    }

    private void enableBrowseBtns(boolean enabled) {
        mDataBinding.btnBrowse.setEnabled(enabled);
        mDataBinding.btnStopBrowse.setEnabled(enabled);
    }
}
